package com.forlove.app.qselect.friend.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseTakePhotoActivity;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.utils.StatusBarCompat;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.manager.QRCodeManager;
import com.forlove.app.manager.async.QRCodeAsync;
import com.forlove.app.qselect.friend.widget.dialog.ShowQRCodeDialog;
import com.forlove.app.qselect.login.widget.SetGpsDialog;
import com.google.zxing.Result;
import com.google.zxing.client.android.Intents;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 扫描二维码界面
 * Created by yjl on 2017/10/23.
 */

@RuntimePermissions
public class ScanQRCodeActivity extends BaseTakePhotoActivity
        implements DecoratedBarcodeView.TorchListener,
        LoaderManager.LoaderCallbacks<Bitmap> {
    private final int scan_image_success = 1000;
    private final int scan_image_fail = 10001;

    @BindView(R.id.btn_switch)
    AppCompatButton swichLight;

    @BindView(R.id.dbv_custom)
    DecoratedBarcodeView mDBV;

    @BindView(R.id.btn_mine_qrcode)
    AppCompatButton btn_mine_qrcode;

    @BindView(R.id.bt_back)
    FrameLayout bt_back;

    @BindView(R.id.text_open_photo)
    TextView text_open_photo;

    @BindView(R.id.view_load_scan)
    RelativeLayout view_load_scan;

    private HandlerThread handlerThread;
    private Handler scanImageHandler;
    private Handler showResultHandler;
    private CaptureManager captureManager;
    private boolean isLightOn = false;
    private SetGpsDialog showInfoDialog;
    private Bitmap QRCodeBitmap;//二维码图片
    private QRCodeAsync qrCodeAsync;
    private ShowQRCodeDialog showQRCodeDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_scan_qrcode;
    }


    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void needStoragePermiss() {
        if (QRCodeBitmap == null || QRCodeBitmap.isRecycled()) {
            view_load_scan.setVisibility(View.VISIBLE);
            getSupportLoaderManager().restartLoader(QRCodeAsync.ASYNC_ID, null, this);
        } else {
            if (showQRCodeDialog == null) {
                showQRCodeDialog = new ShowQRCodeDialog(this, QRCodeBitmap);
            }
            showQRCodeDialog.show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ScanQRCodeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void refuseStoragePermiss() {
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void neverAskAgainPermiss() {
        showTipDialog();
    }

    private QRCodeAsync createQrcodeAnsy() {
        if (qrCodeAsync == null) {

            qrCodeAsync = new QRCodeAsync(this);
        }
        return qrCodeAsync;
    }

    private void showTipDialog() {
        if (showInfoDialog == null) {
            showInfoDialog = new SetGpsDialog(this);
            showInfoDialog.setTextMesseage(getString(R.string.str_storage_reason));
            showInfoDialog.setTitleMsg(getString(R.string.str_storage_permission_title));
            showInfoDialog.setAgreeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PermissionsChecker.gotoPermissionSettings(ScanQRCodeActivity.this);
                    showInfoDialog.dismiss();
                }
            });
        }
        showInfoDialog.show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (showQRCodeDialog != null) {
            showQRCodeDialog.dismiss();
        }
        captureManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
        StatusBarCompat.compat(this, Color.parseColor("#00000000"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
        if (handlerThread != null) {
            handlerThread.quit();
            handlerThread = null;
        }
        if (scanImageHandler != null) {
            scanImageHandler.removeCallbacksAndMessages(null);
            scanImageHandler = null;
        }
        if (showResultHandler != null) {
            showResultHandler.removeCallbacksAndMessages(null);
            showResultHandler = null;
        }
        getSupportLoaderManager().destroyLoader(QRCodeAsync.ASYNC_ID);
        if (showQRCodeDialog != null) {
            showQRCodeDialog.recycle();
            showQRCodeDialog.dismiss();
            showQRCodeDialog = null;
        }
        if (QRCodeBitmap != null) {
            QRCodeBitmap.recycle();
            QRCodeBitmap = null;
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mDBV.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //重要代码，初始化捕获
        captureManager = new CaptureManager(this, mDBV);
        captureManager.initializeFromIntent(getIntent(), savedInstanceState);
        captureManager.decode();
        mDBV.setStatusText("请将二维码放进扫描框内");
        mDBV.getStatusView().setVisibility(View.GONE);
    }

    @Override
    public void initView() {
        mDBV.setTorchListener(this);

        // 如果没有闪光灯功能，就去掉相关按钮
        if (!hasFlash()) {
            swichLight.setVisibility(View.GONE);
        }

    }

    // torch 手电筒
    @Override
    public void onTorchOn() {
//        Toast.makeText(this, "torch on", Toast.LENGTH_LONG).show();
        isLightOn = true;
        swichLight.setText("关闭手电筒");
    }

    @Override
    public void onTorchOff() {
//        Toast.makeText(this, "torch off", Toast.LENGTH_LONG).show();
        isLightOn = false;
        swichLight.setText("开启手电筒");
    }

    // 判断是否有闪光灯功能
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    // 点击切换闪光灯
    @OnClick(R.id.btn_switch)
    public void swichLight() {
        if (isLightOn) {
            mDBV.setTorchOff();
        } else {
            mDBV.setTorchOn();
        }
    }

    @OnClick(R.id.btn_mine_qrcode)
    public void openMineQRCode() {
        //打开我的二维码
        ScanQRCodeActivityPermissionsDispatcher.needStoragePermissWithPermissionCheck(this);
    }

    @OnClick(R.id.bt_back)
    public void onBack() {
        onBackPressed();
    }


    @OnClick(R.id.text_open_photo)
    public void openPhoto() {
        getTakePhoto().onPickFromGallery();
    }

    @Override
    public void takeSuccess(TResult result) {
        if (result != null && result.getImage() != null) {
            TImage tImage = result.getImage();
            String path = tImage.getOriginalPath();
            if (TextUtils.isEmpty(path)) {
                Toast.makeText(this, "获取图片失败,请重新选择!", Toast.LENGTH_SHORT).show();
                view_load_scan.setVisibility(View.GONE);
            } else {
                LogUtil.e("yjl", "相片路径:" + path);
                view_load_scan.setVisibility(View.VISIBLE);
                scanLocalImage(path);
            }

        }

    }

    private synchronized void scanLocalImage(final String path) {
        if (showResultHandler == null) {
            showResultHandler = new Handler(getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == scan_image_fail) {
                        view_load_scan.setVisibility(View.GONE);
                        Toast.makeText(ScanQRCodeActivity.this, "扫描图片失败!", Toast.LENGTH_SHORT).show();
                    } else if (msg.what == scan_image_success) {
                        view_load_scan.setVisibility(View.GONE);
                        Intent intent = getIntent();
                        intent.putExtra(Intents.Scan.RESULT, "" + msg.obj);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                }
            };
        }
        if (handlerThread == null) {
            handlerThread = new HandlerThread("scanImage");
            handlerThread.start();
        }
        if (scanImageHandler == null) {
            scanImageHandler = new Handler(handlerThread.getLooper());
        }
        scanImageHandler.post(new Runnable() {
            @Override
            public void run() {
                Result QRCodeResult = QRCodeManager.decodeBarcodeRGB(path);
                if (QRCodeResult == null
                        || !StringUtils.isNotEmpty(QRCodeResult.getText())) {
                    if (showResultHandler != null) {
                        showResultHandler.sendEmptyMessage(scan_image_fail);
                    }
                } else if (StringUtils.isNotEmpty(QRCodeResult.getText())) {
                    String strReuslt = QRCodeResult.getText();
                    LogUtil.e("yjl", "扫描结果:" + strReuslt);
                    String mobile = "";
                    if (StringUtils.isMobile(strReuslt)) {
                        mobile = strReuslt;
                    } else {
                        String keyStr = CipherUtils.md5(QRCodeManager.scan_key);
                        String decStr = CryptAES.AES_Decrypt(keyStr, strReuslt);
                        if (StringUtils.isMobile(decStr)) {
                            mobile = decStr;
                            LogUtil.e("yjl", "解密扫描结果:" + decStr);
                        }
                    }

                    if (StringUtils.isNotEmpty(mobile)) {
                        Message message = new Message();
                        message.what = scan_image_success;
                        message.obj = mobile;
                        if (showResultHandler != null) {
                            showResultHandler.sendMessage(message);
                        }
                    } else {
                        if (showResultHandler != null) {
                            showResultHandler.sendEmptyMessage(scan_image_fail);
                        }
                    }
                }

            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {
        Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
    }

    @Override
    public Loader<Bitmap> onCreateLoader(int id, Bundle args) {
        return createQrcodeAnsy();
    }

    @Override
    public void onLoadFinished(Loader<Bitmap> loader, Bitmap data) {
        getSupportLoaderManager().destroyLoader(QRCodeAsync.ASYNC_ID);
        QRCodeBitmap = data;
        view_load_scan.setVisibility(View.GONE);
        if (showQRCodeDialog == null && QRCodeBitmap != null) {
            showQRCodeDialog = new ShowQRCodeDialog(this, QRCodeBitmap);
        }
        showQRCodeDialog.show();
    }

    @Override
    public void onLoaderReset(Loader<Bitmap> loader) {
        view_load_scan.setVisibility(View.GONE);
    }
}

